import { CheckOutlined, CopyOutlined } from '@ant-design/icons';
import copy from 'copy-to-clipboard';
import type { MouseEvent } from 'react';
import { useState } from 'react';
import style from './index.less';

interface Props {
  value: string;
  options?: {
    stopBubblingEvent?: boolean;
    durTime?: number;
    copyIconColor?: string;
    successIconColor?: string;
    className?: string;
  };
}

const CopyComponents = (props: Props) => {
  const { value, options } = props;
  const [copyIconShow, setCopyIconShow] = useState<boolean>(true);
  const copyClick = () => {
    copy(value);
    setCopyIconShow(false);
    const timer = setTimeout(
      () => {
        clearTimeout(timer);
        setCopyIconShow(true);
      },
      options?.durTime ? options?.durTime : 1000,
    );
  };
  return (
    <span
      onMouseDown={(e: MouseEvent) => {
        if (options?.stopBubblingEvent) e.stopPropagation();
      }}
      onMouseUp={(e: MouseEvent) => {
        if (options?.stopBubblingEvent) e.stopPropagation();
      }}
      className={options?.className}
    >
      {copyIconShow ? (
        <CopyOutlined
          onClick={copyClick}
          className={style.copyIcon}
          style={{
            color: options?.copyIconColor ? options?.copyIconColor : undefined,
          }}
        />
      ) : (
        <CheckOutlined
          style={{
            color: options?.successIconColor
              ? options?.successIconColor
              : 'rgb(158, 207, 164)',
          }}
        />
      )}
    </span>
  );
};

export default CopyComponents;
